package com.haozi.ehub.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.haozi.ehub.core.enums.ExceptionEnum;
import com.haozi.ehub.core.enums.HttpEunm;
import com.haozi.ehub.core.exception.UsernameOrPasswordErrorException;
import com.haozi.ehub.core.util.CodeUtils;
import com.haozi.ehub.core.util.ResponseUtils;
import com.haozi.ehub.core.util.ReturnDataUtils;
import com.haozi.ehub.entity.entities.ReturnData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆失败,用bean形式使用
 * @author ：terry
 * @date ：Created in 2020/6/23 14:07
 * @description：TODO
 * @version: 1.0
 */
@Slf4j
@SuppressWarnings(value = "all")
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("Execute pacakage core handler securityAuthenticationFailureHandler");
        StringBuilder msg = new StringBuilder(HttpEunm.LOGIN_FAIL.getMsg());

        final String loginValidationFailMsg = ExceptionEnum.LOGIN_VALIDATION_FAIL.getCnmsg();

        //创建处理结果的返回对象
        ReturnData returnData = new ReturnData();

        //判断异常
        if(e instanceof UsernameOrPasswordErrorException
                || e instanceof UsernameNotFoundException){

            msg.append(CodeUtils.COMMA).append(loginValidationFailMsg);
            returnData = ReturnDataUtils.returnDataFail(HttpStatus.INTERNAL_SERVER_ERROR, msg.toString());

        }else{
            returnData = ReturnDataUtils.returnDataFail(HttpStatus.BAD_REQUEST, msg.toString());
        }
        String json = JSONObject.toJSONString(returnData);

        //解决返回数据跨域问题
        ResponseUtils.setHttpSerlvetResponse(httpServletResponse);

        //输出返回结果的JSON
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(json);
        writer.flush();
    }
}
